package com.own.business.resource.core.model;

import com.own.business.resource.core.model.base.BaseUploadModel;
import com.own.component.common.exception.BusinessSimpleException;
import com.own.component.common.util.FileMd5Util;
import com.own.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * UploadModel
 *
 * @author chenxueli
 * @date 2023-07-07 16:44:41
 */
@Slf4j
public class UploadFileModel extends BaseUploadModel {

    /**
     * 文件流信息
     */
    private final File file;

    /**
     * 文件上传
     *
     * @param path 文件路径
     */
    public UploadFileModel(String path) {
        this(new File(path));
    }

    /**
     * 文件上传
     *
     * @param file 文件信息
     */
    public UploadFileModel(File file) {
        this(file, true);
    }

    /**
     * 文件上传
     *
     * @param file    文件信息
     * @param calcMd5 是否计算md5
     */
    public UploadFileModel(File file, boolean calcMd5) {
        if (file == null) {
            throw new BusinessSimpleException(ExceptionEnum.Resource.FILE_NOT_EXIST);
        }
        this.file = file;
        // 获取后缀信息
        this.setOldFileName(file.getName());
        this.setFileSize(file.length());
        if (calcMd5) {
            this.setMd5(FileMd5Util.get(file));
        }
        this.init();
    }

    /**
     * 设置文件流信息
     *
     * @return 文件流信息
     */
    @Override
    public InputStream setInputStream() {
        try {
            return new FileInputStream(file);
        } catch (IOException e) {
            throw new BusinessSimpleException(ExceptionEnum.Resource.INPUT_STREAM_WRROR);
        }
    }

}
